package JavaSocket构造HTTP请求;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HttpClient {
    //实现Get和Post,核心：拼接字符串

    private Socket socket;
    private String ip;
    private int port;

    public HttpClient(String ip, int port) throws IOException {
        this.ip=ip;
        this.port=port;
        socket=new Socket(ip,port);
    }


    //封装一个GET方法
    public String get(String url) throws IOException {
        //1.构造首行
        StringBuilder request=new StringBuilder();
        request.append("GET" + url +"HTTP/1.1 \n");

        //2.构造请求头
        request.append("HOST:"+ip + ":" + port);

        //3.构造空行
        request.append("\n");

        //4.构造body，但是GET请求不需要body

        //5.发送请求，先通过getOutputStream获取outputStream实例
        //  再通过outputStream 写入请求数据，
        //  注意 outputStream是字节流，需要以字节为单位进行写入，因此要把 StringBuilder 转成 byte[]
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());

        //6.读取响应
        InputStream inputStream = socket.getInputStream();
        //  创建一个 1M大小的缓冲区，用来存放响应数据
        byte[] buffer=new byte[1024*1024];
        //  将数据读入到 buffer 中
        int n = inputStream.read(buffer);//n 表示缓冲区中实际用到的字节数

        return new String(buffer,0,n,"utf-8");
    }

    //Post 和 Get 的实现基本一致，只是多了一步 构造body
    public String post(String url,String body) throws IOException {
        //1.构造首行
        StringBuilder request = new StringBuilder();
        request.append("POST" + url + "HTTp/1.1 \n");

        //2.构造请求头
        request.append("Host:"+ ip+ ":" + port+ "\n");
        request.append("Content-type: text/plain \n");
        request.append("Content-length: "+body.getBytes().length + "\n");
        //3.空行
        request.append("\n");
        //4.构造body
        request.append(body);

        //5.发送请求
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());

        //6.读取响应
        InputStream inputStream = socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n = inputStream.read(buffer);

        return new String(buffer,0,n,"utf-8");
    }


    public static void main(String[] args) throws IOException {
        HttpClient httpClient=new HttpClient("42.192.83.143",8089);
        String resp = httpClient.get("/AjaxMockServer/info");
        System.out.println(resp);
    }
}
